package com.yunkaweilai.android.activity;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.base.BaseActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.constants.Umeng;
import com.yunkaweilai.android.fragment.CountFragment;
import com.yunkaweilai.android.fragment.MemberFragment;
import com.yunkaweilai.android.fragment.MyFragment;
import com.yunkaweilai.android.fragment.OperationFragment;
import com.yunkaweilai.android.fragment.OrderFragment;
import com.yunkaweilai.android.interfaces.DialogMemberPayInterface;
import com.yunkaweilai.android.model.Event;
import com.yunkaweilai.android.model.StoreInfoModel;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.utils.InputMethodUtils;
import com.yunkaweilai.android.utils.ThreadUtil;
import com.yunkaweilai.android.utils.Utils;
import com.yunkaweilai.android.view.MyToast;
import com.yunkaweilai.android.view.dialog.UpdateStoreNameDialog;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 主activity
 */
public class MainActivity extends BaseActivity implements RadioGroup.OnCheckedChangeListener, DialogMemberPayInterface {


    @BindView(R.id.id_group)
    RadioGroup mIdGroup;
    @BindView(R.id.id_fLayout_container)
    FrameLayout mIdFLayoutContainer;
    @BindView(R.id.id_rbtn_1)
    RadioButton mIdRbtn1;
    @BindView(R.id.id_rbtn_2)
    RadioButton mIdRbtn2;
    @BindView(R.id.id_rbtn_3)
    RadioButton mIdRbtn3;
    @BindView(R.id.id_rbtn_4)
    RadioButton mIdRbtn4;
    public static final String SELECTOR_HOME_POSITION = "SELECTOR_HOME_POSITION";
    private boolean mDoubleBackExitPressedOnce;
    private OperationFragment mMainFragment;
    private MyFragment mMyFragment;
    private OrderFragment mOrderFragment1;//订单fragment
    //    private CommodityFragment mOrderFragment;
    private CountFragment mOrderFragment;
    private MemberFragment mLiveListFragment;
    private int position = 0; //目前选定的tab位置
    private int old_position = 0;//用于无法选中时返回之前的tab
    private Map<String, Boolean> app_rule;
    private boolean isfirst = true;
    private UpdateStoreNameDialog updateStoreNameDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            mMainFragment = (OperationFragment) fragmentManager.findFragmentByTag("main");
            mOrderFragment1 = (OrderFragment) fragmentManager.findFragmentByTag("member");
            mOrderFragment = (CountFragment) fragmentManager.findFragmentByTag("order");
            mMyFragment = (MyFragment) fragmentManager.findFragmentByTag("my");
        }
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //账号权限获取
        if (BaseApplication.appRuleModel != null) {
            app_rule = BaseApplication.appRuleModel.getApp_rule();
            //是否可以查看订单界面
            if (BaseApplication.appRuleModel.isIs_super() || (app_rule.get("23") != null && app_rule.get("23"))) {

            } else {
                mIdRbtn2.setClickable(false);
                mIdRbtn2.setAlpha((float) 0.3);
            }
            //是否可以查看统计界面
            if (BaseApplication.appRuleModel.isIs_super() || (app_rule.get("3") != null && app_rule.get("3"))) {

            } else {
                mIdRbtn3.setClickable(false);
                mIdRbtn3.setAlpha((float) 0.3);
            }
        } else {
            app_rule = new HashMap<>();
        }


        position = getIntent().getIntExtra(SELECTOR_HOME_POSITION, 0);
        mIdGroup.setOnCheckedChangeListener(this);
        initView(position);
        getStoreInfo();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    //初次进入输入店铺名并保存（当店铺名为：默认店铺名时会触发）
    private void initSave(String x) {
        HttpRequest.postUrl(Api.UPDATE_STORE_NAME)
                .addParams("sub_store_name", x)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            MyToast.showShortToast(mAc, "保存成功！");
                            getStoreInfo();
                            updateStoreNameDialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                        MyToast.showShortToast(mAc, "保存失败！");
                    }
                });

    }

    //获取店铺资料，显示店铺名称
    private void getStoreInfo() {
        HttpRequest.postUrl(Api.STORE_INFO)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        Gson gson = new Gson();
                        boolean checkCode = Utils.checkCode(mAc, json);
                        if (checkCode) {
                            StoreInfoModel storeInfoModel = gson.fromJson(json, StoreInfoModel.class);
                            initDialog(storeInfoModel);
                            mMainFragment.inStoreName(storeInfoModel.getData().getInfo().getStore_name());
                            mMainFragment.refresh();
                        }
                    }

                    @Override
                    public void onError(Exception e) {
                    }
                });
    }

    //如果名字没改过，弹出修改店铺名弹窗
    private void initDialog(StoreInfoModel storeInfoModel) {
        if ("默认店铺名".equals(storeInfoModel.getData().getInfo().getStore_name())) {
            updateStoreNameDialog = new UpdateStoreNameDialog(mAc, this);
            updateStoreNameDialog.setCanceledOnTouchOutside(false);
            updateStoreNameDialog.setCancelable(false);
            updateStoreNameDialog.show();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        InputMethodUtils.closeSoftKeyboard(mAc);
    }

    private void initView(int positions) {
        switch (positions) {
            case 0:
                mIdRbtn1.setChecked(true);
                break;
            case 1:
                mIdRbtn2.setChecked(true);
                break;
            case 2:
                mIdRbtn3.setChecked(true);
                break;
            case 3:
                mIdRbtn4.setChecked(true);
                break;
        }
    }

    //隐藏所有fragment方法，再展示要展示的fragment
    public void hideAllFragment(FragmentTransaction transaction) {
        if (mMainFragment != null) {
            transaction.hide(mMainFragment);
        }
        if (mLiveListFragment != null) {
            transaction.hide(mLiveListFragment);
        }
        if (mOrderFragment != null) {
            transaction.hide(mOrderFragment);
        }
        if (mMyFragment != null) {
            transaction.hide(mMyFragment);
        }
        if (mOrderFragment1 != null) {
            transaction.hide(mOrderFragment1);
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        switch (checkedId) {
            case R.id.id_rbtn_1://首页
                hideAllFragment(transaction);
                if (mMainFragment == null) {
                    mMainFragment = new OperationFragment();
                    transaction.add(R.id.id_fLayout_container, mMainFragment, "main");
                } else {
                    mMainFragment.refresh();
                    transaction.show(mMainFragment);
//                    mMainFragment = new OperationFragment();
//                    transaction.add(R.id.id_fLayout_container, mMainFragment);
                }
                old_position = 0;
                break;
            case R.id.id_rbtn_2:// 订单、退款
//                if (app_rule.get("2")){
//                    hideAllFragment(transaction);
//                    if (mLiveListFragment == null) {
//                        mLiveListFragment = new MemberFragment();
//                        transaction.add(R.id.id_fLayout_container, mLiveListFragment);
//                    } else {
//                        mLiveListFragment.refresh();
//                        transaction.show(mLiveListFragment);
//                    }
//                    old_position = 1;
//                }else{
//                    initView(old_position);
//                }
                if (BaseApplication.appRuleModel.isIs_super() || (app_rule.get("23") != null && app_rule.get("23"))) {
                    hideAllFragment(transaction);
                    MobclickAgent.onEvent(mAc, Umeng.ORDER_REFUND);
                    if (mOrderFragment1 == null) {
                        mOrderFragment1 = new OrderFragment();
                        transaction.add(R.id.id_fLayout_container, mOrderFragment1, "member");

                    } else {
                        mOrderFragment1.refresh();
                        transaction.show(mOrderFragment1);
                    }
                    old_position = 1;
                } else {
                    initView(old_position);
                    showToast("你没有权限");
                }
                break;
            case R.id.id_rbtn_3:// 统计页面
                if (BaseApplication.appRuleModel.isIs_super() || (app_rule.get("3") != null && app_rule.get("3"))) {
                    hideAllFragment(transaction);
                    MobclickAgent.onEvent(mAc, Umeng.COUNT);
                    if (mOrderFragment == null) {
                        mOrderFragment = new CountFragment();
                        transaction.add(R.id.id_fLayout_container, mOrderFragment, "order");
                    } else {
                        mOrderFragment.refresh();
                        transaction.show(mOrderFragment);
                    }
                    old_position = 2;
                } else {
                    initView(old_position);
                    showToast("你没有权限");
                }

                break;
            case R.id.id_rbtn_4:// 我的
                hideAllFragment(transaction);
                MobclickAgent.onEvent(mAc, Umeng.MY);
//                if (isfirst) {
//                    isfirst = false;
//                    transaction.add(R.id.id_fLayout_container, mMyFragment);
//                    transaction.show(mMyFragment);
                if (mMyFragment == null) {
                    mMyFragment = new MyFragment();
                    transaction.add(R.id.id_fLayout_container, mMyFragment, "my");
                } else {
                    mMyFragment.refresh();
                    transaction.show(mMyFragment);
                }
                old_position = 3;
                break;
        }
        transaction.commit();
    }

    /**
     * 1到4三个tab
     *
     * @param event
     */
    @Subscribe
    public void swichTab(Event.TabSwichEvent event) {
        switch (event.mTab) {
            case 1:
                mIdRbtn1.setChecked(true);
                break;
            case 2:
                mIdRbtn2.setChecked(true);
                break;
            case 3:
                mIdRbtn3.setChecked(true);
                break;
            case 4:
                mIdRbtn4.setChecked(true);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        // 双击返回键关闭程序
        // 如果两秒重置时间内再次点击返回,则退出程序
        if (mDoubleBackExitPressedOnce) {
            exit();
            return;
        }
        mDoubleBackExitPressedOnce = true;
        showToast("再按一次返回键关闭程序");
        ThreadUtil.runInUIThread(new Runnable() {
            @Override
            public void run() {
                // 延迟两秒后重置标志位为false
                mDoubleBackExitPressedOnce = false;
            }
        }, 2000);
    }

    // 接口方法 - 修改店铺名
    @Override
    public void passPay(String pass) {
        initSave(pass);
    }
}
